function varargout = Main(varargin)
% MAIN M-file for Main.fig
%      MAIN, by itself, creates a new MAIN or raises the existing
%      singleton*.
%
%      H = MAIN returns the handle to a new MAIN or the handle to
%      the existing singleton*.
%
%      MAIN('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in MAIN.M with the given input arguments.
%
%      MAIN('Property','Value',...) creates a new MAIN or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before Main_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to Main_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help Main

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Main_OpeningFcn, ...
                   'gui_OutputFcn',  @Main_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT



% --- Executes just before Main is made visible.
function Main_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to Main (see VARARGIN)

% Choose default command line output for Main
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);
% UIWAIT makes Main wait for user response (see UIRESUME)
% uiwait(handles.Main);
set(handles.plotPanel,'userdata',struct('vol',{},'mat',{},'alpha',{},...
                                        'colormap',{},'brightness',{},'contrast',...
                                        {},'displayVolume',{},'minmax',{}));
set(handles.cursorPosition,'RowName',[[]]);
set(handles.cursorPosition,'Data', [0 0 0]);
if (~exist(fullfile(pwd,'config.mat')))
    dataFolder = fullfile(getenv('HOMEDRIVE'), getenv('HOMEPATH'), 'ICEM');
else
    config = open(fullfile(pwd,'config.mat'));
    dataFolder = config.dataFolder;
end
appFolder = pwd;
setappdata(gcf,'appFolder',appFolder);
setappdata(gcf,'dataFolder',dataFolder);
%loadlibrary('C:\Users\Ernest\Documents\Matlab\icem\icem_cpp\x64\Debug\cudaicem.dll',...
%    'C:\Users\Ernest\Documents\Matlab\icem\icem_cpp\cudaicem\cudaicem.h');
%To generate the mCudaHeader file, exectue the following command : 
%loadlibrary('C:\Users\Ernest\Documents\Matlab\icem\icem_cpp\x64\Release\cudaicem.dll','C:\Users\Ernest\Documents\Matlab\icem\icem_cpp\cudaicem\cudaicem.h','mfilename','mCudaHeader');
loadlibrary(fullfile(appFolder,'dll','cudaicem.dll'), @mCudaHeader);% ,'alias',alias);
if ~isdir(dataFolder)
    mkdir(dataFolder);
end


% plotPanel.userdata contains the stack with the different modalities being
% viewed :
% 1 : MRI
% 2 : PET
% 3 : Stat map (T-score)
% 4 : EEG source
% 5 : CT
% 6 : electrodes mask
% 7 : CT with electrodes
% 8 : talairach template
% 9 : ROI mask
% 10 : fMRI

% --- Outputs from this function are returned to the command line.
function varargout = Main_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

%==========================================================================
% Menu actions
%==========================================================================




function about_Callback(hObject, eventdata, handles)

% Last Modified by GUIDE v2.5 25-Sep-2013 15:39:43
revision = '$Revision: 67 $';
msgbox({['ICEM ' revision(2:end-1) ' - copyright CRAN'],...
        'Contact : ernest.galbrun@ensem.inpl-nancy.fr',...
        'Source code available at : http://code.google.com/p/icem/',...
        'SPM : http://www.fil.ion.ucl.ac.uk/spm/software/',...
        'Matlab : http://www.mathworks.com/',},...
        'About ICEM');


function manual_Callback(hObject, eventdata, handles)
web https://docs.google.com/document/edit?id=1yRqPxLBb-JW3QM5bmTug_AzmNop9nL2SiTwoVqF0PNo&hl=en&authkey=CJzA6tUO -browser


function SaveBatch_Callback(hObject, eventdata, handles)
IRMPath = get(handles.IRMPath,'TooltipString');
PETPath = get(handles.PETPath,'TooltipString');
statPath = get(handles.statMap,'TooltipString');
CTPath = get(handles.CTPath,'TooltipString');
EEGPath = get(handles.EEGPath,'TooltipString');
fMRIPath = get(handles.fMRIPath,'TooltipString');
electrodesMask = get(handles.displayElectrodes,'TooltipString');
stack = get(handles.plotPanel,'userdata');
Batch.contrast = [];
Batch.brightness = [];
for i=1:length(stack)
    Batch.contrast = [Batch.contrast stack(i).contrast];
    Batch.brightness = [Batch.brightness stack(i).brightness];
end
if ~isempty(IRMPath)
    Batch.IRMPath = IRMPath;
end
if ~isempty(PETPath)
    Batch.PETPath = PETPath;
end
if ~isempty(statPath)
    Batch.statPath = statPath;
end
if ~isempty(CTPath)
    Batch.CTPath = CTPath;
end
if ~isempty(EEGPath)
    Batch.EEGPath = EEGPath;
end
if ~isempty(fMRIPath)
    Batch.fMRIPath = fMRIPath;
end
if ~isempty(electrodesMask)
    Batch.electrodesMask = electrodesMask;
    Batch.electrodesData = get(handles.electrodesTable,'data');
    X = get(handles.electrodesPanel,'userdata');
    Batch.mcaptors = X{4};
end
if ~isempty(get(handles.talairachTable,'userdata'))
    Batch.talairachData = get(handles.talairachTable,'userdata');
end
if ~isempty(get(handles.selectExcisionVolume,'userdata'))
    Batch.excisionData = get(handles.selectExcisionVolume,'userdata');
    Batch.excisionFolder = get(handles.selectExcisionVolume,'TooltipString');
    Batch.excisionList = get(handles.selectExcisionVolume,'string');
end

cd(getappdata(gcf,'dataFolder'));
[FileName,PathName] = uiputfile('*.mat','Select new batch file emplacement');
cd(getappdata(gcf,'appFolder'));
save ([PathName FileName],'Batch');
addlog(handles,['Saving batch file: ' PathName FileName]);


function SelectPETTemplate_Callback(hObject, eventdata, handles)

cd(getappdata(gcf,'dataFolder'));
[file,folder]=uigetfile('*.nii', 'NifTI file','Select PET template');
cd(getappdata(gcf,'appFolder'));
copyfile([folder file], './templates/PET.nii');
addlog(handles,['New PET template: ' folder file]);

function LoadBatch_Callback(hObject, eventdata, handles)

cd(getappdata(gcf,'dataFolder'));
[file,folder]=uigetfile('*.mat', 'ICEM batch file (.mat)','Select batch file');
cd(getappdata(gcf,'appFolder'));
addlog(handles,['Loading batch file : ' folder file]);
if file    
    graphicHandles = DisableAll;
    load([folder file],'Batch');
    if isfield(Batch,'IRMPath')
        [pathstr, name, ext] = fileparts(Batch.IRMPath);
        addlog(handles,['Loading IRM: ' pathstr name ext]);
        set(handles.IRMPath,'tooltipString', Batch.IRMPath,'string',[name ext]);
        if GetVolume([Batch.IRMPath], handles, 1);
        set(handles.displayIRM,'enable','on','value',1);
        set(handles.alphaIRM,'enable','on','value',1);
        set(handles.IRMColormap,'enable','on');
        if (isfield(Batch,'CTPath'))
            set(handles.CoregCT,'enable','on');
        end
        if (isfield(Batch,'PETPath'))
            set(handles.CoregPET,'enable','on');
        end
        set(handles.electrodes,'enable','on');
        set(handles.setTalairach,'enable','on');
        alphaIRM_Callback(handles.alphaIRM,0,handles);
        IRMColormap_Callback(handles.IRMColormap,0,handles);
        SlicePlot(handles,[0 0 0]);
        end
    end
    if isfield(Batch,'PETPath')
        swPETPath = Batch.PETPath;
        [pathstr, name, ext] = fileparts(swPETPath);
        addlog(handles,['Loading PET: ' pathstr name ext]);
        set(handles.PETPath,'TooltipString',swPETPath,'String',[name ext]);
        if GetVolume(fullfile(pathstr, [name(3:end) ext]),handles,2);    
            set(handles.displayPET,'enable','on','value',1);
            set(handles.alphaPET,'enable','on','value',1);
            set(handles.computeStatMap,'enable','on');
            set(handles.PETColormap,'enable','on');
            alphaPET_Callback(handles.alphaPET,0,handles);
            PETColormap_Callback(handles.PETColormap,0,handles);
            SlicePlot(handles,[0 0 0]);
        end
    end
    if isfield(Batch,'statPath')
        [pathstr, name, ext] = fileparts(Batch.statPath);
        addlog(handles,['Loading stat map: ' pathstr name ext]);
        set(handles.statMap,'String',[name ext]);
        set(handles.statMap,'TooltipString',Batch.statPath);
        load(Batch.statPath,'SPM');
        set(handles.Main,'userdata', SPM);    
        [pathstr, name, ext] = fileparts(SPM.xCon.Vspm.fname);
        newImage = fullfile(SPM.swd,['w' name ext]);
        set(handles.statoverlay,'enable','on');
        if GetVolume(newImage,handles,3);
            set(handles.displayStat,'enable','on','value',1);
            set(handles.alphaStat,'enable','on','value',1);
            set(handles.statColormap,'enable','on');
            h = get(handles.statFilter,'children');
            for i =1:length(h)
                set(h(i),'enable','on');
            end
            alphaStat_Callback(handles.alphaStat,0,handles);
            statColormap_Callback(handles.statColormap,0,handles);
            SlicePlot(handles,[0 0 0]);
        end
    end
    if isfield(Batch,'CTPath')
        [pathstr, name, ext] = fileparts(Batch.CTPath);
        addlog(handles,['Loading CT: ' pathstr name ext]);
        set(handles.CTPath,'String',[name ext],'TooltipString',Batch.CTPath);
        if GetVolume(Batch.CTPath, handles, 5);
            set(handles.displayCT,'enable','on','value',1);
            set(handles.alphaCT,'enable','on','value',1);
            set(handles.CTColormap,'enable','on');
            alphaCT_Callback(handles.alphaCT,0,handles);
            CTColormap_Callback(handles.CTColormap,0,handles);
            SlicePlot(handles,[0 0 0]);
        end
    end       
    if isfield(Batch,'EEGPath')
        [pathstr, name, ext] = fileparts(Batch.EEGPath);
        addlog(handles,['Loading EEG: ' pathstr name ext]);
        set(handles.EEGPath,'String',[name ext],'TooltipString',Batch.EEGPath);
        if GetVolume(Batch.EEGPath, handles,4);
            set(handles.displayEEG,'enable','on','value',1);
            set(handles.alphaEEG,'enable','on','value',1);
            set(handles.EEGColormap,'enable','on');
            set(handles.flipEEG,'enable','on')
            alphaEEG_Callback(handles.alphaEEG,0,handles);
            EEGColormap_Callback(handles.EEGColormap,0,handles);
            SlicePlot(handles,[0 0 0]);
        end
    end  
    if isfield(Batch,'fMRIPath')
        [pathstr, name, ext] = fileparts(Batch.fMRIPath);
        addlog(handles,['Loading fMRI: ' pathstr name ext]);
        set(handles.fMRIPath,'String',[name ext],'TooltipString',Batch.fMRIPath);
        if GetVolume(Batch.fMRIPath, handles,10);
            set(handles.displayfMRI,'enable','on','value',1);
            set(handles.alphafMRI,'enable','on','value',1);
            set(handles.fMRIColormap,'enable','on');
            alphafMRI_Callback(handles.alphafMRI,0,handles);
            fMRIColormap_Callback(handles.fMRIColormap,0,handles);
            SlicePlot(handles,[0 0 0]);
        end
    end  
    if isfield(Batch,'electrodesMask')
        [pathstr, name, ext] = fileparts(Batch.electrodesMask);
        addlog(handles,['Loading electrodes mask: ' pathstr name ext]);
        set(handles.displayElectrodes,'String',[name ext],'TooltipString',Batch.electrodesMask);
        if GetVolume(Batch.electrodesMask, handles,6);
            set(handles.displayElectrodes,'enable','on','value',1);
            set(handles.electrodesTable,'enable','on');
            set(handles.showElectrode,'enable','on');
            set(handles.exportElectrodesData,'enable','on');
            set(handles.electrodesTable,'data',Batch.electrodesData);
            set(handles.showElectrode,'string',['Electrode';Batch.electrodesData(:,3)]);
            set(handles.electrodeSelectionROI,'string',['Electrode';Batch.electrodesData(:,3)]);
            stack = get(handles.plotPanel,'userdata');
            if ~cuda
                stack(6).colormap = jet(256);
                set(handles.plotPanel,'userdata',stack);
            else
                calllib('cudaicem','SetColormap',6,jet(256));
            end
            mask = stack(6).vol;
            mask = reshape(mask,1,[]);
            mask = double(mask);
            [a b] = hist(mask,1:256);
            a(1) = 0;
            nonzeroIndexes =find(a);
            cellData = Batch.electrodesData;
            set(handles.electrodesTable,'data',cellData);
            
            electrodesIndexes = cell(length(nonzeroIndexes));
            for i=1:length(nonzeroIndexes)
               electrodesIndexes{i} = find(~(double(stack(6).vol)-nonzeroIndexes(i)));
            end
            set(handles.electrodesPanel,'userdata',{nonzeroIndexes,stack(6).vol,electrodesIndexes,Batch.mcaptors});
            displayElectrodes_Callback(handles.displayElectrodes,0,handles);
            SlicePlot(handles,[0 0 0]);
        end
    end    
    if isfield(Batch,'talairachData')
        set(handles.talairachTable,'userdata',Batch.talairachData);
    end
    if isfield(Batch,'excisionData')
        folder = Batch.excisionFolder;
        set(handles.selectExcisionVolume,'TooltipString',folder,...
            'string',Batch.excisionList,'userdata',Batch.excisionData,'enable','on');
        set(handles.alphaExcision,'enable','on','value',1);
        set(handles.excisionColormap,'enable','on');
        set(handles.displayExcision,'enable','on','value',1);
        set(handles.newExcisionVolume,'enable','on');
        set(handles.exportROI,'enable','on');        
        GetVolume([getappdata(gcf,'appFolder') '\templates\aal.nii'],handles,8,get(handles.talairachTable,'userdata'));
        stack = get(handles.plotPanel,'userdata');
        stack(9).vol = stack(8).vol;
        stack(9).mat = stack(8).mat;    
        stack(9).alpha = 1;
        stack(9).colormap = prism(2000);
        stack(9).brightness = 0;
        stack(9).contrast = 0;
        if cuda
               calllib('cudaicem','ReadTalairachVolume',true,stack(9).alpha,stack(9).brightness,...
                stack(9).contrast,single(stack(9).colormap),single(stack(9).mat),size(stack(9).vol),stack(9).vol,...
                get(handles.talairachTable,'userdata')');    
        end
        set(handles.plotPanel,'userdata',stack);
    end
    stack = get(handles.plotPanel,'userdata');
    if isfield(Batch,'contrast') && isfield (Batch,'brightness')
        for i=1:min(length(stack),length(Batch.contrast))
            stack(i).contrast = Batch.contrast(i);
            stack(i).brightness = Batch.brightness(i);
        end
    end
    set (handles.plotPanel,'userdata',stack);
    SlicePlot(handles,[0 0 0]);
    addlog(handles,'Done.'); 
    EnableAll(graphicHandles);        
end

% --------------------------------------------------------------------
function setDataFolder_Callback(hObject, eventdata, handles)
dataFolder = uigetdir(getappdata(gcf,'dataFolder'));
setappdata(gcf,'dataFolder',dataFolder);
save('config.mat','dataFolder');


% --------------------------------------------------------------------
function statoverlay_Callback(hObject, eventdata, handles)
%[SPM,xSPM] = ComputeFilteredMap(handles);
hyper_hypo = get(handles.analysisType,'String');
hyper_hypo = hyper_hypo{get(handles.analysisType,'Value')};
if get(handles.analysisType,'Value') == 1
    contraste = [1;-1;0;0];
else
    contraste = [-1;1;0;0];
end
k = str2num(get(handles.clusterSize,'String'));
u = str2num(get(handles.valueThreshold,'String'));
% Adding contrast parameters
SPM = get(handles.Main,'userdata');
SPM.xCon=spm_FcUtil('Set',hyper_hypo,'T','c',...
    contraste,SPM.xX.xKXs);
SPM.xCon.name=hyper_hypo;
thresDesc = 'none';
if get(handles.fwe_filter,'value')
    thresDesc = 'FWE';
end
%'FWE'; % was: 'none' more specific less false positive // FWE
xSPM = struct ('Ic',1,'Im',[],'title',hyper_hypo,...
               'thresDesc',thresDesc,'u',u,'k',k,'swd',SPM.swd);
save(fullfile(SPM.swd,'SPM.mat'), 'SPM');
currentFolder = cd;
spm('defaults','PET')
cd (currentFolder);
hReg      = my_spm_results_ui('Setup',xSPM);
[SPM,xSPM] = spm_getSPM(xSPM);
cd (currentFolder);
rendfile = [pwd '\render_single_subj.mat'];
%dat = struct('XYZ',xSPM.XYZ,'t',xSPM.Z','mat',xSPM.M,'dim',SPM.xVol.DIM);
%my_spm_render(dat,1,rendfile);


% --------------------------------------------------------------------
function exportdicom_Callback(hObject, eventdata, handles)
if cuda
    x = libpointer('int32Ptr',0);
    y = libpointer('int32Ptr',0);
    z = libpointer('int32Ptr',0);
    n = libpointer('int32Ptr',0);
    calllib('cudaicem','GetRenderedVolumesNumberAndSize',n,x,y,z);
    vol=libpointer('uint8PtrPtr',zeros(n.value*x.value*y.value*z.value,1,'uint8'));
    mat = libpointer('doublePtrPtr',zeros(16,1));
    names = calllib('cudaicem','GetRenderedVolumes',vol,mat);
    h = spm_vol(get(handles.IRMPath,'TooltipString'));
    exportFolder = uigetdir(getappdata(gcf,'dataFolder'),'Select folder to store dicom files');
    h.mat = reshape(mat.value,4,4);
    medconPath = cd;
    medconPath = ['"' fullfile(medconPath, 'XMedCon', 'bin', 'medcon.exe') '"'];
    for i=1:n.value
        V = vol.value;
        V = V(1+(i-1)*x.value*y.value*z.value:i*x.value*y.value*z.value);
        V = reshape(V,[x.value y.value z.value]);
        h.dim = size(V);
        ptrName = names + (i-1); 
        name = ptrName.value;
        h.fname = fullfile(exportFolder,[name{1} '.nii']);
        f_dcm = fullfile(exportFolder,[name{1} '.dcm']);
        spm_write_vol(h,V);
        if exist(f_dcm,'file')            
            delete(f_dcm)
        end
        system([medconPath ' -f ' h.fname ' -c dicom -o ' f_dcm]) 
    end
end


% --------------------------------------------------------------------
function exportElectrodesData_Callback(hObject, eventdata, handles)

%electrodesCoordinates = cell(3,1);

stack = get(handles.plotPanel,'userdata');
mcaptors = get(handles.electrodesPanel,'userdata');
mcaptors = mcaptors{4};
talM = get(handles.talairachTable,'userdata');
mriCoordinates = [];%cell(length(mcaptors),1);
talairachCoordinates = [];%cell(length(mcaptors),1);
mniCoordinates = [];%cell(length(mcaptors),1);
el = get(handles.electrodesTable,'data');
list = {};
k=1;
for i=1:length(mcaptors)
    captor=mcaptors{i};
    tal = captor;
    mni = captor;
    for j=1:length(captor)
        M=stack(1).mat;
        point = [captor(j,:) 1];
        point = ( M*point')';
        captor(j,:)=point(1:3);
        if ~isempty(talM)
            [mni(j,:),tal(j,:)]=Talairach(point(1:3),talM);
        else
            tal(j,:) = zeros(1,3);
            mni(j,:) = zeros(1,3);            
        end
        list{k} = [el{i,3} num2str(j)];
        k=k+1;
    end
    mriCoordinates = [mriCoordinates; captor];
    talairachCoordinates = [talairachCoordinates; tal];
    mniCoordinates = [mniCoordinates; mni];
end
electrodesCoordinates = struct('mriCoordinates',{mriCoordinates},...
                'talairachCoordinates',{talairachCoordinates},...
                'mniCoordinates',{mniCoordinates});
            
[FileName,PathName,filterIndex] = uiputfile({'*.txt';'*.xls'},'Save electrodes data as...');
if filterIndex==1
    fid = fopen([PathName FileName(1:end-4) '_mri' FileName(end-3:end)],'wt');
    fprintf(fid,'%d %d %d\n',int32(mriCoordinates'));
    fclose(fid);
    fid = fopen([PathName FileName(1:end-4) '_tal' FileName(end-3:end)],'wt');
    fprintf(fid,'%d %d %d\n',int32(talairachCoordinates'));
    fclose(fid);
    fid = fopen([PathName FileName(1:end-4) '_mni' FileName(end-3:end)],'wt');
    fprintf(fid,'%d %d %d\n',int32(mniCoordinates'));
    fclose(fid);
    addlog(handles,['Saving electrodes data file: ' PathName FileName]);
elseif filterIndex==2
    ll = num2str(1+length(mriCoordinates));
    xlswrite([PathName FileName],mriCoordinates,['B2:D' ll]);
    xlswrite([PathName FileName],talairachCoordinates,['E2:G' ll]);
    xlswrite([PathName FileName],mniCoordinates,['H2:J' ll]);
    xlswrite([PathName FileName],{'MRI Coordinates'},'B1:B1')
    xlswrite([PathName FileName],{'Talairach Coordinates'},'E1:E1')
    xlswrite([PathName FileName],{'MNI Coordinates'},'H1:H1')
    xlswrite([PathName FileName],list',['A2:A' ll])  
    
end
    

% --------------------------------------------------------------------
function exportROI_Callback(hObject, eventdata, handles)
desc = get(handles.selectExcisionVolume,'userdata');
[FileName,PathName] = uiputfile('*.txt','Select a new file for ROI description');
fid = fopen([PathName FileName],'wt');
load([getappdata(gcf,'appFolder') '\atlas\AreaList.mat']);
for i=1:length(desc)
    s = get(handles.selectExcisionVolume,'string');
    s = s {i+1};
    fprintf(fid,'Description of ROI: %s\n',s);
    A = desc{i};
    volumes = A.volumeNumbers;
    for j=1:length(volumes)
       name = data{volumes(j)}; 
       fprintf(fid,'Volume # %d: %s\n',j,name);
    end
    el = A.electrodesCutoff;
    dim=size(el);
    for j=1:dim(1)
        electrodes = get(handles.showElectrode,'string');
        el_name = electrodes{el(j,2)};
        dirstring = get(handles.cutoffDirection,'string');
        dir = dirstring{el(j,1)};
        fprintf(fid,'Removing the %s of electrode %s from the ROI\n',dir,el_name);
    end    
end
fclose(fid);
addlog(handles,['Saving ROI description file: ' PathName FileName]);



function CoregPET_Callback(hObject, eventdata, handles)
graphicHandles = DisableAll;
addlog(handles,'Computing coregistration matrix PET->IRM.');
PETPath = get(handles.PETPath,'TooltipString');
[pathstr, name, ext] = fileparts(PETPath);
IRMPath = get(handles.IRMPath,'TooltipString');
VG = spm_vol(IRMPath);
VF = spm_vol(fullfile(pathstr,[name(3:end) ext]));
coreg = spm_coreg(VG,VF);
coreg = inv(spm_matrix(coreg (:)'));
save(fullfile(pathstr,'coreg.dat'),'coreg','-ascii');
GetVolume(fullfile(pathstr,[name(3:end) ext]),handles,2);
SlicePlot (handles, get(handles.cursorPosition,'data'));
alphaPET_Callback(handles.alphaPET,0,handles);
PETColormap_Callback(handles.PETColormap,0,handles);
addlog(handles,'Done.');
EnableAll(graphicHandles);


function CoregCT_Callback(hObject, eventdata, handles)
graphicHandles = DisableAll;
addlog(handles,'Computing coregistration matrix CT->IRM.');
CTPath = get(handles.CTPath,'TooltipString');
[pathstr, name, ext] = fileparts(CTPath);
IRMPath = get(handles.IRMPath,'TooltipString');
VG = spm_vol(IRMPath);
VF = spm_vol(CTPath);
coreg = spm_coreg(VG,VF);
coreg = inv(spm_matrix(coreg (:)'));
save(fullfile(pathstr,'coreg.dat'),'coreg','-ascii');
GetVolume(CTPath,handles,5);
SlicePlot (handles, get(handles.cursorPosition,'data'));
alphaCT_Callback(handles.alphaPET,0,handles);
CTColormap_Callback(handles.PETColormap,0,handles);
addlog(handles,'Done.');
EnableAll(graphicHandles);


function flipEEG_Callback(hObject, eventdata, handles)
graphicHandles = DisableAll;
addlog(handles,'Flipping EEG left/right.');
EEGPath = get(handles.EEGPath, 'tooltipstring');
if exist(EEGPath,'file')
    header = spm_vol(EEGPath);
    vol = spm_read_vols(header);
    header.mat =                [-1  0 0 0;
                                0 1 0 0;
                                0  0 1 0;
                                0  0 0 1] * header.mat;
    spm_write_vol(header,vol);
    GetVolume(EEGPath,handles,4);
    SlicePlot (handles, get(handles.cursorPosition,'data'));    
end
addlog(handles,'Done.');
EnableAll(graphicHandles);



function CTTranslation_Callback(hObject, eventdata, handles)
answer = inputdlg({'x','y','z'},'Enter translation values in mm',1,{'0','0','0'});
stack = get(handles.plotPanel,'userdata');
T = makehgtform('translate',[str2num(answer{1}) str2num(answer{2}) str2num(answer{3})]);
if (length(stack) >= 5)    
    [pathstr, name, ext] = fileparts(get(handles.CTPath,'TooltipString'));
    if exist(fullfile(pathstr,'coreg.dat'))
        coreg = load(fullfile(pathstr,'coreg.dat'));
        coreg = T * coreg;
        save(fullfile(pathstr,'coreg.dat'),'coreg','-ascii');
    end    
    stack(5).mat = T * stack(5).mat;
    set(handles.plotPanel,'userdata',stack);    
    GetVolume(get(handles.CTPath,'TooltipString'),handles,5);
    SetColormap(5,handles,handles.CTColormap);
    SlicePlot (handles,get(handles.cursorPosition,'data'));    
end

  
function eegTranslation_Callback(hObject, eventdata, handles)
answer = inputdlg({'x','y','z'},'Enter translation values in mm',1,{'0','0','0'});
stack = get(handles.plotPanel,'userdata');
T = makehgtform('translate',[str2num(answer{1}) str2num(answer{2}) str2num(answer{3})]);
if (length(stack) >= 4)    
    [pathstr, name, ext] = fileparts(get(handles.EEGPath,'TooltipString'));
    if exist(fullfile(pathstr,'coreg.dat'))
        coreg = load(fullfile(pathstr,'coreg.dat'));
        coreg = T * coreg;
    else
        coreg = T;
    end    
    save(fullfile(pathstr,'coreg.dat'),'coreg','-ascii');
    stack(4).mat = T * stack(4).mat;
    set(handles.plotPanel,'userdata',stack); 
    GetVolume(get(handles.EEGPath,'TooltipString'),handles,4);   
    SetColormap(4,handles,handles.EEGColormap);
    SlicePlot (handles,get(handles.cursorPosition,'data'));    
end  

function PETTranslation_Callback(hObject, eventdata, handles)
answer = inputdlg({'x','y','z'},'Enter translation values in mm',1,{'0','0','0'});
stack = get(handles.plotPanel,'userdata');
T = makehgtform('translate',[str2num(answer{1}) str2num(answer{2}) str2num(answer{3})]);
if (length(stack) >= 2)    
    [pathstr, name, ext] = fileparts(get(handles.PETPath,'TooltipString'));
    if exist(fullfile(pathstr,'coreg.dat'))
        coreg = load(fullfile(pathstr,'coreg.dat'));
        coreg = T * coreg;
    else
        coreg = T;
    end  
    save(fullfile(pathstr,'coreg.dat'),'coreg','-ascii');  
    stack(2).mat = T * stack(2).mat;
    set(handles.plotPanel,'userdata',stack);
    GetVolume(get(handles.PETPath,'TooltipString'),handles,2); 
    SetColormap(2,handles,handles.PETColormap);
    SlicePlot (handles,get(handles.cursorPosition,'data'));    
end


function electrodesTranslation_Callback(hObject, eventdata, handles)
answer = inputdlg({'x','y','z'},'Enter translation values in mm',1,{'0','0','0'});
stack = get(handles.plotPanel,'userdata');
T = makehgtform('translate',[str2num(answer{1}) str2num(answer{2}) str2num(answer{3})]);
if (length(stack) >= 6)    
    [pathstr, name, ext] = fileparts(get(handles.displayElectrodes,'TooltipString'));
    if exist(fullfile(pathstr,'coreg.dat'))
        coreg = load(fullfile(pathstr,'coreg.dat'));
        coreg = T * coreg;
        save(fullfile(pathstr,'coreg.dat'),'coreg','-ascii');
    end    
    stack(6).mat = T * stack(6).mat;
    set(handles.plotPanel,'userdata',stack);
    SlicePlot (handles,get(handles.cursorPosition,'data'));
end




% --------------------------------------------------------------------
function SetFilterLimits_Callback(hObject, eventdata, handles)
answer = inputdlg({'min/max p value'},'Enter filter limit',1,{'0.5'});
p = str2double(answer{1});
if p==0.5
    lower_ = 0;
    upper = 0;
else
    stack = get(handles.plotPanel,'userdata');
    header=spm_vol(get(handles.fMRIPath,'TooltipString'));
    A=spm_read_vols(header);
    A=reshape(A,1,numel(A));
    [n,xout] = hist(double(A),(min(A):1:max(A)));
    m=find(n==max(n));
    if (m>1 && m<length(n))
        n(m) = mean([n(m-1) n(m+1)]);
    end
    %xout = xout-xout(find(n==max(n)));
    B = cumsum(n); 
    n = n/B(length(B));
    mu = sum(xout.*n);
    sigma = sqrt(sum((xout-mu).*(xout-mu).*n));
    B=(B-B(1))/(B(length(B))-B(1));
    cm = get(handles.fMRIColormap,'string');
    cm = lower(cm{get(handles.fMRIColormap,'value')});
    new_cm = gray(256);
    if p>0.5
        lower_ = 0;
        upper = 255/(max(A)-min(A)) * find(B>=p,1);
        stack(10).minmax = min(A) + [upper 255] / 255 * (max(A)-min(A)); 
        range = 256-int32(upper)+1;
        cm = single(eval([cm '(' num2str(range) ')']));
        new_cm(int32(upper):256,:) = cm;
    else
        lower_ = 255/(max(A)-min(A)) * find(B<=p,1);
        upper = 0;
        stack(10).minmax = min(A) + [0 lower_] / 255 * (max(A)-min(A));
        range = int32(lower_);
        cm = single(eval([cm '(' num2str(range) ')']));
        new_cm(1:int32(lower_),:) = cm;
    end
    B=2*B -1; % should be equal to erf(x/sqrt(2))
    scale = sqrt(2) * erfinv(p) / xout(find(B>p,1));
    xout = xout * scale;
    stack(10).minmax  = (stack(10).minmax-mu) /sigma;
    set(handles.plotPanel,'userdata',stack);   
    calllib('cudaicem','SetColormap',10,new_cm);
end
calllib('cudaicem','SetFilterLimits',10,lower_, upper);
SlicePlot (handles, get(handles.cursorPosition,'data'));


function electrodes_Callback(hObject, eventdata, handles)
graphicHandles = DisableAll;
addlog(handles,'Loading CT with electrodes.');

cd(getappdata(gcf,'dataFolder'));
[file,folder]=uigetfile('*.nii;*.img;*.*', 'NIfTI (.nii);Analyse (.img)',...
                        'multiSelect','on','Select CT with electrodes ; select multiple files for sliced DICOM conversion.');
cd(getappdata(gcf,'appFolder'));
if iscell(file)
    addlog(handles,'Converting DICOM data to NiftII format.')
    newFile = UnsliceDicom(folder,file);
    [folder, name, ext] = fileparts(newFile);
    file = [name ext];
end
if (~file)
    addlog(handles,'Done.');
    EnableAll(graphicHandles);
    return;
end
    
lonmri = get(handles.IRMPath,'TooltipString');
lonct = fullfile(folder,file);
GetVolume(lonct,handles,7);
addlog(handles,'Detection of electrodes.');
[out coid CC] = find_in_ct(lonct,handles.plotPanel);
mcaptors = find_multi_captors(out, coid, CC);
addlog(handles,'Coregistration CT->IRM.');
[x A B] = spm_coreg_modif(lonmri,lonct);
%allel = vertcat(mcaptors{:});
stack = get(handles.plotPanel,'userdata');
fgm1 = uint8(zeros(size(stack(1).vol)));
mcaptors_MRI = cell(length(mcaptors),1);
for j=1:length(mcaptors)
    % Insert white points (as electrodes) in MRI
    allel = mcaptors{j};
    PP = allel*A' + repmat(B',length(allel(:,1)),1);
    PP2 = round(PP);
    mcaptors_MRI{j} = PP2;

    %X1 = analyze75read(lonmri);
    %Y1 = mat2gray(X1);
    %P = im2uint8(Y1);
    %P = zeros(size(stack(1).vol));
    %clear X1 Y1
    for i=1:length(PP2(:,1))
        x = PP2(i,1);
        y = PP2(i,2);
        z = PP2(i,3);
        
        fgm1(x,y,z) = j;
        fgm1(x+1,y,z) = j;
        fgm1(x,y+1,z) = j;
        fgm1(x,y,z+1) = j;
        fgm1(x-1,y,z) = j;
        fgm1(x,y-1,z) = j;
        fgm1(x,y,z-1) = j;
    end
end

%se1 = strel('disk', 1);
%c = imdilate(fgm1, se1);

%P(logical(c)) = 255;

% Save .IMG/.HDR
%nii = load_nii(lonmri);
%nii.img = int16(P);
%save_nii(nii,'ana2.hdr');
header = spm_vol(lonmri);
header.fname=[header.fname(1:end-4) '_Emask.nii'];
set(handles.displayElectrodes,'tooltipString',header.fname);
spm_write_vol(header,fgm1);

GetVolume(header.fname, handles,6);

stack = get(handles.plotPanel,'userdata');
mask = stack(6).vol;
mask = reshape(mask,1,[]);
mask = double(mask);
[a b] = hist(mask,1:256);
a(1) = 0;
nonzeroIndexes =find(a);
cellData = cell(length(nonzeroIndexes),3);
electrodesIndexes = cell(length(nonzeroIndexes));
 for i=1:length(nonzeroIndexes)
    color = rgbconv(stack(6).colormap(nonzeroIndexes(i),:));
    cellData(i,:) = {true,...
        ['<html><body bgcolor=' color '>&nbsp &nbsp &nbsp &nbsp</html>'],...
        ''};
    %find indexes of all element with ith value
    electrodesIndexes{i} = find(~(double(stack(6).vol)-nonzeroIndexes(i)));
 end

set(handles.electrodesTable,'data',cellData);
set(handles.showElectrode,'string',['Electrode';cellData(:,3)]);
set(handles.electrodeSelectionROI,'string',['Electrode';cellData(:,3)]);
set(handles.displayElectrodes,'enable','on','value',1);
set(handles.electrodesTable,'enable','on');
set(handles.exportElectrodesData,'enable','on');
set(handles.showElectrode,'enable','on');
set(handles.electrodesPanel,'userdata',{nonzeroIndexes,stack(6).vol,electrodesIndexes,mcaptors_MRI});
displayElectrodes_Callback(handles.displayElectrodes,0,handles);
addlog(handles,'Done.');
SlicePlot (handles, get(handles.cursorPosition,'data'));
EnableAll(graphicHandles);


% --- Executes on button press in validateTalairach.
function validateTalairach_Callback(hObject, eventdata, handles)
set(hObject,'userdata',clock)

% --------------------------------------------------------------------
function setTalairach_Callback(hObject, eventdata, handles)
set(handles.validateTalairach,'enable','on');
M = zeros(3,9);
IDlist = {'AC','PC','IHP','AP','PP','SP','IP','RP','LP'};
for i=1:9
    addlog(handles,['Go to ' IDlist{i} ' and press continue.']);
    waitfor(handles.validateTalairach,'userdata');
    M(:,i) = get(handles.cursorPosition,'data');
end
set(handles.talairachTable,'userdata',M);
set(handles.validateTalairach,'enable','off');
addlog(handles,'Done.');

%==========================================================================
% SELECT FILES
%==========================================================================


function selectIRM_Callback(hObject, eventdata, handles)
stack = get(handles.plotPanel,'userdata');
cd(getappdata(gcf,'dataFolder'));
[file,folder]=uigetfile('*.nii;*.img;*.*', 'NIfTI (.nii);Analyse (.img)',...
                        'multiSelect','on','Select IRM ; select multiple files for sliced DICOM conversion.');
cd(getappdata(gcf,'appFolder'));
if iscell(file)
    graphicHandles = DisableAll;
    addlog(handles,'Converting DICOM data to NiftII format.')
    newFile = UnsliceDicom(folder,file);
    [folder, name, ext] = fileparts(newFile);
    file = [name ext];
    EnableAll(graphicHandles);
end
if file    
    addlog(handles,['Loading IRM: ' fullfile(folder,file)]);
    graphicHandles = DisableAll;
    set(handles.IRMPath,'String',file);
    set(handles.IRMPath,'TooltipString',fullfile(folder,file));
    if GetVolume(fullfile(folder,file), handles, 1);
        set(handles.displayIRM,'enable','on','value',1);
        set(handles.alphaIRM,'enable','on','value',1);
        set(handles.IRMColormap,'enable','on');
        if (~isempty(get(handles.CTPath,'String')))
            set(handles.CoregCT,'enable','on');
        end
        if (~isempty(get(handles.PETPath,'String')))
            set(handles.CoregPET,'enable','on');
        end
        set(handles.electrodes,'enable','on');
        set(handles.setTalairach,'enable','on');
        alphaIRM_Callback(handles.alphaIRM,0,handles);
        IRMColormap_Callback(handles.IRMColormap,0,handles);
        SlicePlot (handles, get(handles.cursorPosition,'data'));
    end
    addlog(handles,'Done.');
    EnableAll(graphicHandles);
end

function SelectPET_Callback(hObject, eventdata, handles)
graphicHandles = DisableAll;
try    
    cd(getappdata(gcf,'dataFolder'));
    [file,folder]=uigetfile('*.*;*.nii;*.dcm', 'DICOM (.IMA);NifTI (.nii)',...
    'multiSelect','on','Select PET-Scan');
    cd(getappdata(gcf,'appFolder'));
if iscell(file)
    addlog(handles,'Converting DICOM data to NiftII format.')
    newFile = UnsliceDicom(folder,file);
    [folder, name, ext] = fileparts(newFile);
    file = [name ext];
end    
    addlog(handles,['Loading PET: ' fullfile(folder,file)]);
    swPETPath = PETConv(fullfile(folder,file));
    [pathstr, name, ext] = fileparts(swPETPath);
    set(handles.PETPath,'String',[name ext]);
    set(handles.PETPath,'TooltipString',swPETPath);
    if GetVolume(fullfile(pathstr, [name(3:end) ext]),handles,2);    
        set(handles.displayPET,'enable','on','value',1);
        set(handles.alphaPET,'enable','on','value',1);
        set(handles.PETColormap,'enable','on');    
        set(handles.computeStatMap,'enable','on');
        if (~strcmp(get(handles.IRMPath,'String'),''))
            set(handles.CoregPET,'enable','on');
        end
        alphaPET_Callback(handles.alphaPET,0,handles);
        PETColormap_Callback(handles.PETColormap,0,handles);
        SlicePlot (handles, get(handles.cursorPosition,'data'));
    end
end
addlog(handles,'Done.');
EnableAll(graphicHandles);
    
function selectStatMap_Callback(hObject, eventdata, handles)
cd(getappdata(gcf,'dataFolder'));
[file,folder]=uigetfile('*.MAT', 'SPM.mat)','Select stat file');
cd(getappdata(gcf,'appFolder'));
addlog(handles,['Loading stat map: ' folder file]);
if file
    graphicHandles = DisableAll;
    set(handles.statMap,'String',file,'TooltipString',[folder file]);
    load([folder file],'SPM');
    set(handles.Main,'userdata', SPM);
    [pathstr, name, ext] = fileparts(SPM.xCon(1).Vspm.fname);
    newImage = fullfile(SPM.swd,['w' name ext]);    
    set(handles.statoverlay,'enable','on');
    if GetVolume(newImage,handles,3);
        set(handles.displayStat,'enable','on','value',1);
        set(handles.alphaStat,'enable','on','value',1);
        set(handles.statColormap,'enable','on');        
        alphaStat_Callback(handles.alphaStat,0,handles);
        statColormap_Callback(handles.statColormap,0,handles);
        SlicePlot (handles, get(handles.cursorPosition,'data'));
        h = get(handles.statFilter,'children');
        for i =1:length(h)
            set(h(i),'enable','on');
        end
    end
    addlog(handles,'Done.');
    EnableAll(graphicHandles);
end
    
function selectEEG_Callback(hObject, eventdata, handles)
stack = get(handles.plotPanel,'userdata');
cd(getappdata(gcf,'dataFolder'));
[file,folder]=uigetfile('*.nii;*.img', 'NIfTI (.nii);Analyse (.img)','Select EEG');
cd(getappdata(gcf,'appFolder'));
if file
    addlog(handles,['Loading EEG: ' folder file]);
    set(gcf,'pointer','watch');
    graphicHandles = DisableAll;
    set(handles.EEGPath,'String',file,'TooltipString',[folder file]);
    if GetVolume([folder file], handles, 4);
        set(handles.displayEEG,'enable','on','value',1);
        set(handles.alphaEEG,'enable','on','value',1);
        set(handles.EEGColormap,'enable','on');        
        set(handles.flipEEG,'enable','on')
        alphaEEG_Callback(handles.alphaEEG,0,handles); 
        EEGColormap_Callback(handles.EEGColormap,0,handles);
        SlicePlot (handles, get(handles.cursorPosition,'data'));
    end
    set(handles.flipEEG,'enable','on')
    set(gcf,'pointer','arrow');
    addlog(handles,'Done.');
    EnableAll(graphicHandles);
end;

    
function selectCT_Callback(hObject, eventdata, handles)
stack = get(handles.plotPanel,'userdata');
graphicHandles = DisableAll;
cd(getappdata(gcf,'dataFolder'));
[file,folder]=uigetfile('*.*;*.nii;*.img;*.IMA;*.dcm', 'NIfTI (.nii);Analyse (.img); DICOM (.IMA); DICOM(.dcm)','Select CT',...
                        'multiSelect','on');
cd(getappdata(gcf,'appFolder'));
if iscell(file)
    addlog(handles,'Converting DICOM data to NiftII format.')
    newFile = UnsliceDicom(folder,file);
    [folder, name, ext] = fileparts(newFile);
    file = [name ext];
end
if file
    set(handles.CTPath,'String',file,'TooltipString',fullfile(folder,file));
    if GetVolume(fullfile(folder,file), handles, 5);
    addlog(handles,['Loading CT: ' fullfile(folder,file)]);
        set(handles.displayCT,'enable','on','value',1);
        set(handles.alphaCT,'enable','on','value',1);
        set(handles.CTColormap,'enable','on');
        if (~strcmp(get(handles.IRMPath,'String'),''))
            set(handles.CoregCT,'enable','on');
        end
        alphaCT_Callback(handles.alphaCT,0,handles);
        CTColormap_Callback(handles.CTColormap,0,handles);
        SlicePlot (handles, get(handles.cursorPosition,'data'));
    end
end;
addlog(handles,'Done.');
EnableAll(graphicHandles);


function selectfMRI_Callback(hObject, eventdata, handles)
stack = get(handles.plotPanel,'userdata');
graphicHandles = DisableAll;
cd(getappdata(gcf,'dataFolder'));
[file,folder]=uigetfile('*.*;*.nii;*.img;*.IMA;*.dcm', 'NIfTI (.nii);Analyse (.img); DICOM (.IMA); DICOM(.dcm)','Select CT',...
                        'multiSelect','on');
cd(getappdata(gcf,'appFolder'));
if iscell(file)
    addlog(handles,'Converting DICOM data to NiftII format.')
    newFile = UnsliceDicom(folder,file);
    [folder, name, ext] = fileparts(newFile);
    file = [name ext];
end
if file
    set(handles.fMRIPath,'String',file,'TooltipString',fullfile(folder,file));
    if GetVolume(fullfile(folder,file), handles, 10);
    addlog(handles,['Loading fMRI: ' fullfile(folder,file)]);
        set(handles.displayfMRI,'enable','on','value',1);
        set(handles.alphafMRI,'enable','on','value',1);
        set(handles.fMRIColormap,'enable','on');
        alphafMRI_Callback(handles.alphafMRI,0,handles);
        fMRIColormap_Callback(handles.fMRIColormap,0,handles);
        SlicePlot (handles, get(handles.cursorPosition,'data'));
    end
end;
addlog(handles,'Done.');
EnableAll(graphicHandles);



%==========================================================================
% EXCISION STUFF
%==========================================================================


% --- Executes on button press in excision.
function excision_Callback(hObject, eventdata, handles)
graphicHandles = DisableAll;
addlog(handles,'Loading anatomic atlas');
GetVolume([getappdata(gcf,'appFolder') '\templates\aal.nii'],handles,8,get(handles.talairachTable,'userdata'));
[fo fi ext] = fileparts(get(handles.IRMPath,'tooltipstring'));
folder = uigetdir(fo,'Select a folder to save ROI volume data');
SlicePlot (handles, get(handles.cursorPosition,'data'));
set(handles.selectExcisionVolume,'TooltipString',folder);
set(handles.selectExcisionVolume,'String','Full atlas','enable','on');
set(handles.alphaExcision,'enable','on','value',1);
set(handles.excisionColormap,'enable','on');
set(handles.displayExcision,'enable','on','value',1);
set(handles.newExcisionVolume,'enable','on');
addlog(handles,'Done.');
EnableAll(graphicHandles);



% --- Executes on selection change in selectExcisionVolume.
function selectExcisionVolume_Callback(hObject, eventdata, handles)
stack = get(handles.plotPanel,'userdata');
if (get(hObject,'value'))~=1
    i = get(hObject,'value');
    desc = get(hObject,'userdata');
    desc = desc{i-1};
    N = desc.volumeNumbers;   
    cutoffData = desc.electrodesCutoff;
    stack = get(handles.plotPanel,'userdata');
    V = uint16(zeros(size(stack(8).vol)));
    for i=1:length(N)
        V = V+ ( stack(8).vol .* uint16((stack(8).vol==N(i))));
    end
    stack(9).vol = ApplyCutoff(handles,V,stack(8).mat,stack(1).mat,cutoffData);    
    stack(8).alpha = 0;
    stack(9).alpha = get(handles.alphaExcision,'value') * get(handles.displayExcision,'value');
else    
    stack(9).alpha = 0;
    stack(8).alpha = get(handles.alphaExcision,'value') * get(handles.displayExcision,'value');
end
if cuda
    calllib('cudaicem','ReadTalairachVolume',true,stack(9).alpha,stack(9).brightness,...
        stack(9).contrast,single(stack(9).colormap),single(stack(9).mat),size(stack(9).vol),stack(9).vol,...
        get(handles.talairachTable,'userdata')');    
    calllib('cudaicem','SetAlpha',8,stack(8).alpha);
    calllib('cudaicem','SetAlpha',9,stack(9).alpha);
end
set(handles.plotPanel,'userdata',stack);
SlicePlot (handles, get(handles.cursorPosition,'data'));


% --- Executes on button press in newExcisionVolume.
function newExcisionVolume_Callback(hObject, eventdata, handles)
addlog(handles,'Select the volume(s) you want to add.');
addlog(handles,'Click "done" when you are finished');
set(handles.electrodeSelectionROI,'enable','on');
set(handles.addvolume,'enable','on');
set(handles.done,'enable','on');
set(handles.electrodeCutoff,'enable','on');
set(handles.cutoffDirection,'enable','on');



% --- Executes on button press in addvolume.
function addvolume_Callback(hObject, eventdata, handles)
pos = get(handles.cursorPosition,'data');
pos = [pos 1];
stack = get(handles.plotPanel,'userdata');
M = stack(8).mat;
pos = M\pos';
V = stack(8).vol;
pos = int16(pos(1:3));
try
    N = V(pos(1),pos(2),pos(3));
    if N~=0
        NN = get(hObject,'userdata');
        set(hObject,'userdata',[NN N]);
        name = get(handles.selectedArea,'string');
        name = name{2};
        addlog(handles,['Adding volume: ' name '.']);
    end
catch
    a=0;
end


% --- Executes on button press in electrodeCutoff.
function electrodeCutoff_Callback(hObject, eventdata, handles)
stack = get(handles.plotPanel,'userdata');
dir = get(handles.cutoffDirection,'value');
electrode = get(handles.electrodeSelectionROI,'value') - 1;
dirstring = get(handles.cutoffDirection,'string');
dirstring = dirstring{dir};
addlog(handles,['Adding an electrode cuttoff at the '...
    dirstring ' of electrode number ' num2str(electrode) '.']);
set(hObject,'userdata',[get(hObject,'userdata');[dir,electrode]]);




% --- Executes on button press in done.
function done_Callback(hObject, eventdata, handles)
N = get(handles.addvolume,'userdata');
set(handles.addvolume,'userdata',[]);
name = inputdlg({'name: '},'Enter the name of the new defined volume');
name = name{1};
stack = get(handles.plotPanel,'userdata');
V = uint16(zeros(size(stack(8).vol)));
for i=1:length(N)
    V = V+ ( stack(8).vol .* uint16((stack(8).vol==N(i))));
end
if length(stack) < 9
    if length(stack)~=1
        for j=length(stack)+1:8
            stack = [stack struct('vol',uint8(zeros(size(V.vol))),'mat',makehgtform(),...
                                      'colormap',gray(256),'alpha',0,'brightness',0,'contrast',0)]; %#ok<AGROW>
        end
    end
end
stack(8).alpha = 0;
stack(9).vol = V;
stack(9).mat = stack(8).mat;    
stack(9).alpha = 1;
stack(9).colormap = prism(2000);
stack(9).brightness = 0;
stack(9).contrast = 0;
set(handles.plotPanel,'userdata',stack);
a = get(handles.selectExcisionVolume,'string');
if (~iscell(a))
    set(handles.selectExcisionVolume,'string', {a;name});
else
    set(handles.selectExcisionVolume,'string', [a;name]);
end

cutoffData = get(handles.electrodeCutoff,'userdata');
stack(9).vol=ApplyCutoff(handles,stack(9).vol,stack(9).mat,stack(1).mat,cutoffData);
set(handles.plotPanel,'userdata',stack);
if cuda
    calllib('cudaicem','SetAlpha',8,0);
    calllib('cudaicem','ReadTalairachVolume',true,stack(9).alpha,stack(9).brightness,...
        stack(9).contrast,single(stack(9).colormap),stack(9).mat,size(stack(9).vol),stack(9).vol,...
        get(handles.talairachTable,'userdata')');    
end
volumeDescription = struct('volumeNumbers',N,'electrodesCutoff',cutoffData);
desc = get(handles.selectExcisionVolume,'userdata');
i = length(get(handles.selectExcisionVolume,'string'));
if length(desc)<i
    desc = [desc;volumeDescription];
else
    desc(i-1) = volumeDescription;
end    
set(handles.selectExcisionVolume,'userdata',desc);
set(handles.selectExcisionVolume,'value',i);
set(handles.addvolume,'enable','off');
set(handles.done,'enable','off');
set(handles.electrodeCutoff,'enable','off');
set(handles.electrodeCutoff,'userdata',[]);
set(handles.cutoffDirection,'enable','off');
set(handles.exportROI,'enable','on');
set(handles.electrodeSelectionROI,'enable','off');
SlicePlot (handles, get(handles.cursorPosition,'data'));

function vol_out = ApplyCutoff(handles,vol_in,mat,electrodeMat,cutoffData)
vol_out = vol_in;
for l=1:size(cutoffData,1)
    
    electrode = cutoffData(l,2)-1;
    dir = cutoffData(l,1);
    coord = get(handles.electrodesPanel,'userdata');
    coord = coord{4}{electrode};
    M2=zeros(length(coord),3);
    for i=1:length(coord)
        M1 = coord(i,:);
        M=electrodeMat;
        M1 = [M1 1];
        M1 = ( M*M1')';
        M2(i,:) = M1(1:3);
    end
    concernedVolume = zeros(length(M2),1);
    for i=1:length(M2)   
        M3 = [M2(i,:) 1];
        M3 = mat\M3';
        pos = int16(M3(1:3));
        try
            N = vol_in(pos(1),pos(2),pos(3));
            if N~=0
               concernedVolume(i)=N;
            end
        end
    end
    V = M2(end,:)-M2(1,:); %V is unary vector
    V = V ./ norm(V);
    axis = round(dir/2); %axis =1 (x) 2 (y) 3 (z)
    dim = size(vol_in);
    sign = mod(dir,2);
    if sign==0
        sign=-1;
    end
    for i=1:dim(1)
        if max(max(vol_in(i,:,:)))~=0
            for j=1:dim(2)
                if (max(vol_in(i,j,:)))~=0
                    for k=1:dim(3)
                        if vol_in(i,j,k)~=0 && max(vol_in(i,j,k)==concernedVolume)        
                            p = [i j k 1];
                            p = (mat*p')';
                            p = p(1:3);
                            P = M2(1,:) + V * dot (p-M2(1,:),V);
                            P=P-p;
                            if (P(axis)*sign)<0
                                vol_out(i,j,k) = 0;
                            end
                        end
                    end
                end
            end
        end
    end
end
    
%==========================================================================
% TRANSPARENCY
%==========================================================================


function SetTransparency(i,handles,alphaHandle,displayHandle)
if (cuda)
   calllib('cudaicem','SetAlpha',i,single(get(alphaHandle,'value') * get(displayHandle,'value'))); 
else
    stack = get(handles.plotPanel,'userdata');
    stack(i).alpha = get(alphaHandle,'value') * get(displayHandle,'value');
    set(handles.plotPanel,'userdata',stack);
end
SlicePlot (handles, get(handles.cursorPosition,'data'));

function alphaIRM_Callback(hObject, eventdata, handles)
SetTransparency(1,handles,hObject,handles.displayIRM);
if length(get(handles.plotPanel,'userdata'))>=6
    SetTransparency(6,handles,hObject,handles.displayIRM);
end

function alphaPET_Callback(hObject, eventdata, handles)
SetTransparency(2,handles,hObject,handles.displayPET);

function alphaStat_Callback(hObject, eventdata, handles)
SetTransparency(3,handles,hObject,handles.displayStat);

function alphaEEG_Callback(hObject, eventdata, handles)
SetTransparency(4,handles,hObject,handles.displayEEG);

function alphaCT_Callback(hObject, eventdata, handles)
SetTransparency(5,handles,hObject,handles.displayCT);

function alphaExcision_Callback(hObject, eventdata, handles)
if (get(handles.selectExcisionVolume,'value') == 1)
    SetTransparency(8,handles,hObject,handles.displayExcision);
else
    SetTransparency(9,handles,hObject,handles.displayExcision);
end

function alphafMRI_Callback(hObject, eventdata, handles)
SetTransparency(10,handles,hObject,handles.displayfMRI);

%==========================================================================
% COLORMAP
%==========================================================================

function SetColormap(i,handles,cmhandle)
cm = get(cmhandle,'string');
cm = lower(cm{get(cmhandle,'value')});
if ~cuda
    stack = get(handles.plotPanel,'userdata');
    stack(i).colormap = eval([cm '(256)']);
    set(handles.plotPanel,'userdata',stack);
else
    calllib('cudaicem','SetColormap',i,single(eval([cm '(256)'])));
end
SlicePlot (handles, get(handles.cursorPosition,'data'));

function IRMColormap_Callback(hObject, eventdata, handles)
SetColormap(1,handles,hObject);

function PETColormap_Callback(hObject, eventdata, handles)
SetColormap(2,handles,hObject);

function statColormap_Callback(hObject, eventdata, handles)
SetColormap(3,handles,hObject);

function EEGColormap_Callback(hObject, eventdata, handles)
SetColormap(4,handles,hObject);

function CTColormap_Callback(hObject, eventdata, handles)
SetColormap(5,handles,hObject);

function excisionColormap_Callback(hObject, eventdata, handles)
if (get(handles.selectExcisionVolume,'value') == 1)
    SetColormap(8,handles,hObject);
else
    SetColormap(9,handles,hObject);
end

function fMRIColormap_Callback(hObject, eventdata, handles)
SetColormap(10,handles,hObject);
%==========================================================================
% DISPLAY
%==========================================================================

function displayIRM_Callback(hObject, eventdata, handles)
SetTransparency(1,handles,handles.alphaIRM,hObject);

function displayPET_Callback(hObject, eventdata, handles)
SetTransparency(2,handles,handles.alphaPET,hObject);

function displayStat_Callback(hObject, eventdata, handles)
SetTransparency(3,handles,handles.alphaStat,hObject);

function displayEEG_Callback(hObject, eventdata, handles)
SetTransparency(4,handles,handles.alphaEEG,hObject);

function displayCT_Callback(hObject, eventdata, handles)
SetTransparency(5,handles,handles.alphaCT,hObject);

function displayExcision_Callback(hObject, eventdata, handles)
if (get(handles.selectExcisionVolume,'value') == 1)
    SetTransparency(8,handles,handles.alphaExcision,hObject);
else
    SetTransparency(9,handles,handles.alphaExcision,hObject);
end

function displayElectrodes_Callback(hObject, eventdata, handles)
if length(get(handles.plotPanel,'userdata')) >= 6    
    SetTransparency(6,handles,handles.alphaIRM,hObject);
end


function displayfMRI_Callback(hObject, eventdata, handles)
if length(get(handles.plotPanel,'userdata')) >= 10    
    SetTransparency(10,handles,handles.alphafMRI,hObject);
end

function clusterSize_Callback(hObject, eventdata, handles)


function valueThreshold_Callback(hObject, eventdata, handles)


function analysisType_Callback(hObject, eventdata, handles)

function computeStatMap_Callback(hObject, eventdata, handles)
graphicHandles = DisableAll;
addlog(handles,'Computing new stat map.');
SPM = AncovaTest(get(handles.PETPath,'TooltipString'), handles.log);
set(handles.statMap,'String', fullfile('SPM.mat'));
set(handles.statMap,'TooltipString', fullfile(SPM.swd,'SPM.mat'));
addlog(handles,['New stat map saved: ' fullfile(SPM.swd,'SPM.mat')]);
addlog(handles,['Creating constrast volume.'])
save(fullfile(SPM.swd,'SPM.mat'),'SPM');
set(handles.Main,'userdata',SPM);
hyper_hypo = get(handles.analysisType,'String');
hyper_hypo = hyper_hypo{get(handles.analysisType,'Value')};
k = str2num(get(handles.clusterSize,'String'));
u = str2num(get(handles.valueThreshold,'String'));
% Adding contrast parameters
SPM.xCon=spm_FcUtil('Set',hyper_hypo,'T','c',...
    [1;-1;0;0],SPM.xX.xKXs);
SPM.xCon.name=hyper_hypo;
thresDesc = 'none';
if get(handles.fwe_filter,'value')
    thresDesc = 'FWE';
end
xSPM = struct ('Ic',1,'Im',[],'title',hyper_hypo,...
               'thresDesc',thresDesc,'u',u,'k',k,'swd',SPM.swd); %thresdesc was: none
save(fullfile(SPM.swd,'SPM.mat'), 'SPM');
% Spm_getSPM uses SPM file, so we need to save it before calling the
% function. Also, this function changes the current directory ; We
% need to set it back after the call.
[SPM,xSPM] = spm_getSPM(xSPM);
cd (getappdata(gcf,'appFolder'));
set(handles.Main,'userdata', SPM);
swPETPath = SPM.xY.VY(1).fname;
[pathstr, name, ext] = fileparts(swPETPath);
snPath = fullfile(pathstr, [name(3:end) '_sn.mat']);
% Display raw T-Score map
addlog(handles,'Displaying raw T-score map.');
newImage = RevertNormalisation(fullfile(SPM.swd,SPM.xCon.Vspm.fname),snPath);
if GetVolume(newImage,handles,3);
    set(handles.displayStat,'enable','on','value',1);
    set(handles.alphaStat,'enable','on','value',1);
    set(handles.statColormap,'enable','on');
    h = get(handles.statFilter,'children');
    for i =1:length(h)
        set(h(i),'enable','on');
    end
    alphaStat_Callback(handles.alphaStat,0,handles);
    statColormap_Callback(handles.statColormap,0,handles);
    SlicePlot(handles,get(handles.cursorPosition,'data'));
end
addlog(handles,'Done.');
EnableAll(graphicHandles);

function analysePETStats_Callback(hObject, eventdata, handles)
graphicHandles = DisableAll;
addlog(handles,'Computing new filtered map.');
[SPM,xSPM] = ComputeFilteredMap(handles);
if isempty(xSPM.Z)
    addlog(handles,lastwarn);
    EnableAll(graphicHandles);
    return;
end    
set(handles.Main,'userdata', SPM);
swPETPath = SPM.xY.VY(1).fname;
[pathstr, name, ext] = fileparts(swPETPath);
snPath = fullfile(pathstr, [name(3:end) '_sn.mat']);
im = blobs2vol(xSPM.XYZ,xSPM.Z,xSPM.M);
imgHeader = struct('fname',fullfile(SPM.swd,'filterdTScore.img'),...
                   'dim',im.dim,'dt',[64 0],'mat',im.mat);
spm_write_vol(imgHeader,im.imgdata);
addlog(handles,['Reverting normalization.']);
newImage = RevertNormalisation(fullfile(SPM.swd,'filterdTScore.img'),snPath);
if GetVolume(newImage,handles,3);
    set(handles.displayStat,'enable','on','value',1);
    set(handles.alphaStat,'enable','on','value',1);
    set(handles.statColormap,'enable','on');
    alphaStat_Callback(handles.alphaStat,0,handles);
    statColormap_Callback(handles.statColormap,0,handles);
    SlicePlot(handles,get(handles.cursorPosition,'data'));
end
set(handles.statoverlay,'enable','on');
addlog(handles,'Done.');
EnableAll(graphicHandles);

function [SPM,xSPM] = ComputeFilteredMap(handles)
hyper_hypo = get(handles.analysisType,'String');
hyper_hypo = hyper_hypo{get(handles.analysisType,'Value')};
if get(handles.analysisType,'Value') == 1
    contraste = [1;-1;0;0];
else
    contraste = [-1;1;0;0];
end
k = str2num(get(handles.clusterSize,'String'));
u = str2num(get(handles.valueThreshold,'String'));
% Adding contrast parameters
SPM = get(handles.Main,'userdata');
SPM.xCon=spm_FcUtil('Set',hyper_hypo,'T','c',...
    contraste,SPM.xX.xKXs);
SPM.xCon.name=hyper_hypo;
thresDesc = 'none';
if get(handles.fwe_filter,'value')
    thresDesc = 'FWE';
end
xSPM = struct ('Ic',1,'Im',[],'title',hyper_hypo,...
               'thresDesc',thresDesc,'u',u,'k',k,'swd',SPM.swd);
save(fullfile(SPM.swd,'SPM.mat'), 'SPM');
currentFolder = cd;
% Spm_getSPM uses SPM file, so we need to save it before calling the
% function. Also, this function changes the current directory ; We
% need to set it back after the call.
[SPM,xSPM] = spm_getSPM(xSPM);
cd (currentFolder);


function cursorPosition_CellEditCallback(hObject, eventdata, handles)
SlicePlot (handles, get(handles.cursorPosition,'data'));


function Main_ResizeFcn(hObject, eventdata, handles)
scrsz = get(gcf,'position');
panelPos = get(handles.controlPanel,'position');
set(handles.plotPanel,'position',[panelPos(3)+1 -1 scrsz(3)-panelPos(3)-137 scrsz(4)-1]);
set(handles.controlPanel,'position',[1 scrsz(4)-panelPos(4)-2 panelPos(3) panelPos(4)]);
set(handles.electrodesPanel,'position',[scrsz(3)-136 scrsz(4)-panelPos(4)-2 136 panelPos(4)]);

function PETColormap_CreateFcn(hObject, eventdata, handles) 

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function EEGColormap_CreateFcn(hObject, eventdata, handles) %#ok<*INUSD,*DEFNU>

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function statColormap_CreateFcn(hObject, eventdata, handles)

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function alphaIRM_CreateFcn(hObject, eventdata, handles)

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

function alphaPET_CreateFcn(hObject, eventdata, handles)

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

function alphaEEG_CreateFcn(hObject, eventdata, handles)

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

function alphaStat_CreateFcn(hObject, eventdata, handles)

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

function IRMColormap_CreateFcn(hObject, eventdata, handles)

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function Main_WindowButtonDownFcn(src,event,guidata)
function plotPanel_ButtonDownFcn(src,event,guidata)


function alphaCT_CreateFcn(hObject, eventdata, handles)

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end


function CTColormap_CreateFcn(hObject, eventdata, handles)

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function clusterSize_CreateFcn(hObject, eventdata, handles)

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function valueThreshold_CreateFcn(hObject, eventdata, handles)

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function analysisType_CreateFcn(hObject, eventdata, handles)

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% DisableAll and Enable are called at the begining and end of callback
% function with much calculation. Disable all searches every active object
% and set them as inactive, and makes the cursor a sandglass. EnableAll
% sets these objects back as active

function h = DisableAll()
set (gcf,'pointer','watch');
h= findobj('enable','on');
for i=1:length(h)
    try
    set(h(i),'enable','inactive');
    catch ME
    end
end
drawnow;

function EnableAll(h)
set (gcf,'pointer','arrow');
for i=1:length(h)
    set(h(i),'enable','on');
end

function addlog(handles,str)
set(handles.log,'string',[{str};(get(handles.log,'string'))]);
drawnow;

function MainMenu_Callback(hObject, eventdata, handles)

function Transform_Callback(hObject, eventdata, handles)


function Untitled_1_Callback(hObject, eventdata, handles)


% --- Executes on button press in displayElectrodes.


% --- Executes when entered data in editable cell(s) in electrodesTable.
function electrodesTable_CellEditCallback(hObject, eventdata, handles)
if (eventdata.Indices(2)==1)
    graphicHandles = DisableAll;
    cellData = get(handles.electrodesTable,'data');
    stack = get(handles.plotPanel,'userdata');
    defaultData = get(handles.electrodesPanel,'userdata');
    electrodesIndexes = defaultData{3};
    for i=1:length(cellData)
        %find indexes of all element with ith value

        stack(6).vol(electrodesIndexes{i}) = uint8(cellData{i,1}) * defaultData{2}(electrodesIndexes{i}); %#ok<FNDSB>
    end
    set(handles.plotPanel,'userdata',stack);
    SlicePlot (handles, get(handles.cursorPosition,'data'));
    EnableAll(graphicHandles);
elseif (eventdata.Indices(2)==3)
    cellData = get(handles.electrodesTable,'data');
    set(handles.showElectrode,'string',['Electrode';cellData(:,3)]);
end

    


function outHtml = colText(inText, inColor)
% return a HTML string with colored font
outHtml = ['<html><body bgcolor="', ...
inColor, ...
'">', ...
inText, ...
'</font></html>'];


% --- Executes on selection change in selectElectrode.
function showElectrode_Callback(hObject, eventdata, handles)
if get(hObject,'Value')~=1
    mcaptors = get(handles.electrodesPanel,'userdata');
    mcaptors = mcaptors{4};
    mcaptor = mcaptors{get(hObject,'Value')-1};
    set(handles.electrodeNumber,'string',{'Number';num2str((1:length(mcaptor))')});
    set(handles.electrodeNumber,'Value',1);
    set(handles.electrodeNumber,'enable','on');
end


% --- Executes on selection change in electrodeNumber.
function electrodeNumber_Callback(hObject, eventdata, handles)
if get(hObject,'Value')~=1 
    mcaptors = get(handles.electrodesPanel,'userdata');
    mcaptors = mcaptors{4};
    
    mcaptor = mcaptors{get(handles.showElectrode,'Value')-1};
    point = mcaptor(get(hObject,'Value')-1,:);
    stack = get(handles.plotPanel,'userdata');
    M=stack(1).mat;
    point = [point 1];
    point = ( M*point')';
    SlicePlot (handles,point(1:3));    
    
end



% --- Executes during object creation, after setting all properties.
function selectElectrode_CreateFcn(hObject, eventdata, handles)
% hObject    handle to selectElectrode (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end




% --- Executes during object creation, after setting all properties.
function electrodeNumber_CreateFcn(hObject, eventdata, handles)
% hObject    handle to electrodeNumber (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end




% --- Executes during object creation, after setting all properties.
function showElectrode_CreateFcn(hObject, eventdata, handles)
% hObject    handle to showElectrode (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function brightnessContrastSelect_Callback(hObject, eventdata, handles)
i = get(hObject,'value');
stack = get(handles.plotPanel,'userdata');
if length(stack) >= i
    set(handles.brightness,'value',stack(i).brightness);
    set(handles.contrast,'value',stack(i).contrast);
end


function brightnessContrastSelect_CreateFcn(hObject, eventdata, handles)

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function brightness_Callback(hObject, eventdata, handles)
i = get(handles.brightnessContrastSelect,'value');
stack = get(handles.plotPanel,'userdata');
if (length(stack) >=i)
    if cuda
        calllib('cudaicem','SetBrightness',i,get(hObject,'value'));
    else
        stack(i).brightness = get(hObject,'value');
        set(handles.plotPanel,'userdata',stack);
    end  
    SlicePlot (handles,get(handles.cursorPosition,'data'));  
end

function contrast_Callback(hObject, eventdata, handles)
i = get(handles.brightnessContrastSelect,'value');
stack = get(handles.plotPanel,'userdata');
if (length(stack) >=i)
    if cuda
        calllib('cudaicem','SetContrast',i,get(hObject,'value'));
    else
        stack(i).brightness = get(hObject,'value');
        set(handles.plotPanel,'userdata',stack);    
    end
    SlicePlot (handles,get(handles.cursorPosition,'data'));
end


function brightness_CreateFcn(hObject, eventdata, handles)

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end


function contrast_CreateFcn(hObject, eventdata, handles)

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end


% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end




% --- Executes during object creation, after setting all properties.
function alphaExcision_CreateFcn(hObject, eventdata, handles)
% hObject    handle to alphaExcision (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes during object creation, after setting all properties.
function excisionColormap_CreateFcn(hObject, eventdata, handles)
% hObject    handle to excisionColormap (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



% --- Executes during object creation, after setting all properties.
function selectExcisionVolume_CreateFcn(hObject, eventdata, handles)
% hObject    handle to selectExcisionVolume (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in cutoffDirection.
function cutoffDirection_Callback(hObject, eventdata, handles)
% hObject    handle to cutoffDirection (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns cutoffDirection contents as cell array
%        contents{get(hObject,'Value')} returns selected item from cutoffDirection


% --- Executes during object creation, after setting all properties.
function cutoffDirection_CreateFcn(hObject, eventdata, handles)
% hObject    handle to cutoffDirection (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in popupmenu15.
function popupmenu15_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu15 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu15 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu15


% --- Executes during object creation, after setting all properties.
function popupmenu15_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu15 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in electrodeSelectionROI.
function electrodeSelectionROI_Callback(hObject, eventdata, handles)
% hObject    handle to electrodeSelectionROI (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns electrodeSelectionROI contents as cell array
%        contents{get(hObject,'Value')} returns selected item from electrodeSelectionROI


% --- Executes during object creation, after setting all properties.
function electrodeSelectionROI_CreateFcn(hObject, eventdata, handles)
% hObject    handle to electrodeSelectionROI (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes when user attempts to close Main.
function Main_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to Main (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: delete(hObject) closes the figure
unloadlibrary('cudaicem');
delete(hObject);


% --------------------------------------------------------------------
function rotate_using_electrode_Callback(hObject, eventdata, handles)
if get(handles.showElectrode,'Value')~=1 
    mcaptors = get(handles.electrodesPanel,'userdata');
    mcaptors = mcaptors{4};
    
    points = mcaptors{get(handles.showElectrode,'Value')-1};
    A = points(1,:) - points(length(points),:);
    if A(2)~=0
        theta = 360/(2*pi) * atan(A(3)/A(2));
    else
        theta = 0;        
    end
    if theta>pi/4
        theta = theta - pi/2;
    elseif theta < -pi/4
        theta = pi/2 + theta;
    end
    set(handles.rotation,'userdata',theta);   
    stack = get(handles.plotPanel,'userdata'); 
    for i=1:length(stack)
        M = makehgtform('xrotate',theta) * stack(i).mat;
        calllib('cudaicem','SetTransformationMatrix',i,M);
    end
    SlicePlot (handles,get(handles.cursorPosition,'data'));  
end

% --------------------------------------------------------------------
function rotate_using_points_Callback(hObject, eventdata, handles)

panelHandle = handles.plotPanel;
children = (get(panelHandle,'children'));
children = flipud(children);
h = imline(children(5));
P = h.getPosition;
P = P(1,:)-P(2,:);
P = [0; P(1); P(2); 1];
theta = get(handles.rotation,'userdata');
if isempty(theta)
    theta = 0;
end
P = makehgtform('xrotate',theta) \P;
if (P(2)~=0)
    theta = -atan(P(3)/P(2));
else
    theta = 0;
end
if theta>pi/4
    theta = theta - pi/2;
elseif theta < -pi/4
    theta = pi/2 + theta;
end
       
set(handles.rotation,'userdata',theta);
stack = get(handles.plotPanel,'userdata'); 
for i=1:length(stack)
    M = makehgtform('xrotate',theta) * stack(i).mat;
    calllib('cudaicem','SetTransformationMatrix',i,M);
end
SlicePlot (handles,get(handles.cursorPosition,'data'));  


function rotate_using_points_Y_Callback(hObject, eventdata, handles)
panelHandle = handles.plotPanel;
children = (get(panelHandle,'children'));
children = flipud(children);
h = imline(children(3));
P = h.getPosition;
P = P(2,:)-P(1,:);
P = [P(1); 0; P(2); 1];
theta = get(handles.rotate_using_points_Y,'userdata');
if isempty(theta)
    theta = 0;
end
P = makehgtform('yrotate',theta) \P;
if (P(1)~=0)
    theta = atan(P(3)/P(1));
else
    theta = 0;
end
if theta>pi/4
    theta = theta - pi/2;
elseif theta < -pi/4
    theta = pi/2 + theta;
end       
set(handles.rotate_using_points_Y,'userdata',theta);
stack = get(handles.plotPanel,'userdata'); 
for i=1:length(stack)
    M = makehgtform('yrotate',theta) * stack(i).mat;
    calllib('cudaicem','SetTransformationMatrix',i,M);
end
SlicePlot (handles,get(handles.cursorPosition,'data'));  

function rotate_using_points_Z_Callback(hObject, eventdata, handles)
panelHandle = handles.plotPanel;
children = (get(panelHandle,'children'));
children = flipud(children);
h = imline(children(1));
P = h.getPosition;
P = P(2,:)-P(1,:);
P = [P(1); P(2); 0; 1];
theta = get(handles.rotate_using_points_Z,'userdata');
if isempty(theta)
    theta = 0;
end
P = makehgtform('zrotate',theta) \P;
if (P(1)~=0)
    theta = -atan(P(2)/P(1));
else
    theta = 0;
end
if theta>pi/4
    theta = theta - pi/2;
elseif theta < -pi/4
    theta = pi/2 + theta;
end       
set(handles.rotate_using_points_Z,'userdata',theta);
stack = get(handles.plotPanel,'userdata'); 
for i=1:length(stack)
    M = makehgtform('zrotate',theta) * stack(i).mat;
    calllib('cudaicem','SetTransformationMatrix',i,M);
end
SlicePlot (handles,get(handles.cursorPosition,'data'));  




% --------------------------------------------------------------------
function rotate_angle_Callback(hObject, eventdata, handles)
theta_x = get(handles.rotation,'userdata');
theta_y = get(handles.rotate_using_points_Y,'userdata');
theta_z = get(handles.rotate_using_points_Z,'userdata');

if isempty(theta_x)
    theta_x = 0;
end
if isempty(theta_y)
    theta_y = 0;
end
if isempty(theta_z)
    theta_z = 0;
end
stack = get(handles.plotPanel,'userdata');
answer = inputdlg({'angle Axial:', 'angle Frontal:', 'angle Sagittal:'},...
    'Enter rotation value in degrees',1,...
    {num2str(theta_z*180/pi), num2str(theta_y*180/pi), num2str(theta_x*180/pi)});
theta_z = str2double(answer{1})*2*pi/360;
theta_y = str2double(answer{2})*2*pi/360;
theta_x = str2double(answer{3})*2*pi/360;

for i=1:length(stack)
    M = makehgtform('xrotate',theta_x) * makehgtform('yrotate',theta_y)...
        * makehgtform('zrotate',theta_z) * stack(i).mat;
    calllib('cudaicem','SetTransformationMatrix',i,M);
end
SlicePlot (handles,get(handles.cursorPosition,'data'));
set(handles.rotate_using_points_Z,'userdata',theta_z);
set(handles.rotate_using_points_Y,'userdata',theta_y);
set(handles.rotation,'userdata',theta_x);


% --------------------------------------------------------------------
function ResetRotation_Callback(hObject, eventdata, handles)
stack = get(handles.plotPanel,'userdata');
for i=1:length(stack)
    M = stack(i).mat;
    calllib('cudaicem','SetTransformationMatrix',i,M);
end
SlicePlot (handles,get(handles.cursorPosition,'data'));
set(handles.rotation,'userdata',0);
set(handles.rotate_using_points_Z,'userdata',0);
set(handles.rotate_using_points_Y,'userdata',0);


function alphafMRI_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes during object creation, after setting all properties.
function fMRIColormap_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in fwe_filter.
function fwe_filter_Callback(hObject, eventdata, handles)
% hObject    handle to fwe_filter (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of fwe_filter
